<template>
  <div>
    <el-card class="box-card">
      <el-row>
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/main/department' }">权限管理</el-breadcrumb-item>
          <el-breadcrumb-item>角色管理</el-breadcrumb-item>
        </el-breadcrumb>
      </el-row>
      <el-row><br><br></el-row>
      <el-row>
        <el-col :span="1"><br></el-col>
        <el-col :span="19">
          <el-form :inline="true" :model="dto" class="form-inline" ref="dtoForm">
            <el-form-item prop="name">
              <el-input v-model="dto.name" placeholder="请输入角色名称"></el-input>
            </el-form-item>
            <el-form-item prop="did">
              <el-select v-model="dto.did" clearable placeholder="请选择所属部门">
                <el-option
                  v-for="item in departmentList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>         
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="1"><br></el-col>
        <el-col :span="7">
          <el-button type="primary" icon="el-icon-search" @click="getRoleList()">搜索</el-button>
          <el-button type="warning" @click="resetForm('dtoForm')">重置</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="success" round @click="handleAdd()">添加角色</el-button>
        </el-col>
      </el-row>
      <el-row><br><br></el-row>
      <el-row>
        <el-col :span="1"><br></el-col>
        <el-col :span="18">
          <el-table
            :data="roleList"
            style="width: 100%"
            height="310">
            <el-table-column
              label="序号"
              type="index"
              width="60">
            </el-table-column>
            <el-table-column
              prop="name"
              label="角色名称"
              width="170">
            </el-table-column>
            <el-table-column
              prop="department.name"
              label="所属部门"
              width="120">
            </el-table-column>
            <el-table-column
              prop="remark"
              label="备注"
              width="200">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope"> 
                <el-button
                  size="mini" type="primary" icon="el-icon-edit"
                  @click="handleEdit(scope.row)">编辑</el-button>
                <el-button
                  size="mini" type="warning"
                  @click="handlePerms(scope.row)">授权</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  :disabled = "scope.row.id == 1"
                  @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row><br></el-row>
      <el-row>
        <el-col :span="1"><br></el-col>
        <el-col :span="5">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="dto.page"
            :page-sizes="[5, 10, 20, 30]"
            :page-size="dto.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </el-col>
      </el-row>
    </el-card>
    <!-- 表单弹出框 -->
    <el-dialog :title="formtitle" :visible.sync="dialogRoleVisible" width="30%" @close="close('ruleForm')"  :modal-append-to-body="false">
      <el-form :model="role" :rules="currentRules" ref="ruleForm">
        <el-form-item label="角色名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="role.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色部门" :label-width="formLabelWidth" prop="did">
          <el-select v-model="role.did" clearable placeholder="请选择所属部门">
            <el-option
              v-for="item in departmentList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色备注" :label-width="formLabelWidth" prop="remark">
          <el-input v-model="role.remark" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close('ruleForm')">取 消</el-button>
        <el-button type="primary" @click="handleConfirm('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 展示权限的抽屉 -->
    <el-drawer
      title="权限列表"
      :visible.sync="drawerTableVisible"
      direction="rtl"
      size="35%"
      :modal-append-to-body="false">
      <el-col :span="2"><br></el-col>
      <el-col :span="22">
        <el-table :data="permsList">
          <el-table-column
            label="序号"
            type="index"
            width="50">
          </el-table-column>
          <el-table-column
            prop="name"
            label="权限名"
            width="100">
          </el-table-column>
          <el-table-column
            prop="description"
            label="权限描述"
            width="120">
          </el-table-column>
          <el-table-column label="操作">
              <template slot-scope="scope"> 
                <el-button
                  size="mini" type="primary" icon="el-icon-edit"
                  @click="handleEditPerms(scope.row)">编辑</el-button>
                <el-popconfirm
                  title="此操作将永久删除该权限,确定删除吗？"
                  @confirm="handleDeletePerms(scope.row)">
                  <el-button
                  size="mini"
                  type="danger"
                  slot="reference"
                  >删除</el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
        </el-table>
        <el-pagination
          @current-change="handlePermsCurrentChange"
          :current-page.sync="page"
          :page-size="size"
          layout="total, prev, pager, next"
          :total="permsTotal">
        </el-pagination>
        <el-divider></el-divider>
        <el-row>
          <span style="font-size: 20px;">添加权限</span>
        </el-row>  
        <el-row><br></el-row>
        <el-col :span="18">
          <el-form :model="perms" :rules="permsRules" ref="permsForm">
            <el-form-item label="权限名称" :label-width="formLabelWidth" prop="name">
              <el-input v-model="perms.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="权限描述" :label-width="formLabelWidth" prop="description">
              <el-input v-model="perms.description" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
          <el-button type="primary" @click="addPerms('permsForm')">添加</el-button>
        </el-col>
      </el-col>
    </el-drawer>
    <el-dialog title="编辑权限" :visible.sync="dialogPermsVisible" width="30%" @close="close('editPermsForm')"  :modal-append-to-body="false">
      <el-form :model="newPerms" :rules="permsRules" ref="editPermsForm">
        <el-form-item label="权限名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="newPerms.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="权限描述" :label-width="formLabelWidth" prop="description">
          <el-input v-model="newPerms.description" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close('editPermsForm')">取 消</el-button>
        <el-button type="primary" @click="handleConfirmPerms('editPermsForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var validateCheckName = (rule, value, callback) => {
      if (this.formtitle == '编辑角色' && this.role.name == this.oldRole.name && this.role.did == this.oldRole.did && this.role.remark == this.oldRole.remark){
        callback(new Error('请至少修改一项数据'));
      } else if (this.formtitle == '编辑角色' && this.role.name == this.oldRole.name){
        callback();
      } else {
        this.$axios.get('/role/checkName/' + value).then(res=>{
          if (res.data.code == 200) {
            if (res.data.data) {
              callback();
            } else {
              callback(new Error('您输入的名称已存在'));
            }
          }
        })
      }
    };
    return {
      dto:{
        name:'',
        did:'',
        page:1,
        size:5
      },
      departmentList:[],
      roleList:[],
      total:0,
      dialogRoleVisible:false,
      formtitle:'',
      formLabelWidth: '80px',
      role:{
        id:'',
        name:'',
        did:'',
        remark:''
      },
      oldRole:{},
      currentRules:{},
      ruleAdd:{
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { validator: validateCheckName, trigger: 'blur' }
        ],
        did: [
          { required: true, message: '请选择部门', trigger: 'change' }
        ],
      },
      ruleEdit:{
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { validator: validateCheckName, trigger: 'blur' }
        ],
        did: [
          { required: true, message: '请选择部门', trigger: 'change' },
          { validator: validateCheckName, trigger: 'change' }
        ],
        remark: [
          { validator: validateCheckName, trigger: 'blur' }
        ],
      },
      drawerTableVisible: false,
      permsList:[],
      page:1,
      size:5,
      permsTotal:0,
      permsTitle:'',
      perms:{
        id:'',
        name:'',
        description:'',
        rid:''
      },
      newPerms:{
        id:'',
        name:'',
        description:''
      },
      permsRules:{
        name:[
          { required: true, message: '请输入权限名称', trigger: 'blur' },
        ]
      },
      dialogPermsVisible: false,
    }
  },
  watch:{
     // 监听title的变化，动态切换规则集
     formtitle(newTitle) {
      this.currentRules = newTitle === '添加部门' ? this.ruleAdd : this.ruleEdit;
      // 如果需要，可以在这里触发表单的重新验证
      //this.$refs.ruleForm.validate();
    }
  },
  mounted() {
    this.getAllDepartmentList()
    this.getRoleList()
  },
  methods: {
    handleSizeChange(val) {
      this.dto.size = val
      this.getRoleList()
    },
    handleCurrentChange(val){
      this.dto.page = val
      this.getRoleList()
    },
    //重置查询表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    getAllDepartmentList(){
      this.$axios.get('/department/getAllDepartmentList').then(res=>{
        this.departmentList = res.data.data
      })
    },
    getRoleList(){
      this.$axios.get('/role/getRoleList',{
        params:this.dto
      }).then(res=>{
        this.roleList = res.data.data.data
        this.total = res.data.data.total
      })
    },
    close(formName){
      this.$refs[formName].clearValidate();
      this.dialogRoleVisible = false
      this.dialogPermsVisible = false
    },
    handleAdd(){
      this.dialogRoleVisible = true
      this.formtitle = "添加角色"
      this.role = {
        id:'',
        name:'',
        did:'',
        remark:''
      }
    },
    handleEdit(row){
      this.oldRole = row
      this.dialogRoleVisible = true
      this.formtitle = "编辑角色"
      this.role = {
        id: row.id,
        name: row.name,
        did: row.did,
        remark: row.remark
      }
    },
    handleConfirm(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.formtitle == '添加角色') {
            this.$axios.post('/role/addRole',this.role).then(res=>{
              if (res.data.code == 200) {
                this.$message({
                  message: '添加成功！',
                  type: 'success'
                });
                this.dialogRoleVisible = false
                this.getRoleList()
              }
            })
          }
          if (this.formtitle == '编辑角色') {
            this.$axios.put('/role/editRole',this.role).then(res=>{
              if (res.data.code == 200) {
                this.$message({
                  message: '编辑成功！',
                  type: 'success'
                });
                this.dialogRoleVisible = false
                this.getRoleList()
              }
            })
          }     
        } else {
          return false;
        }
      }); 
    },
    handleDelete(row){
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.delete('/role/deleteRole/' + row.id).then(res=>{
          if (res.data.code == 200) {
            if (res.data.data){
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.getRoleList()
            }
          }
          if(res.data.code == 502){
            this.$message.error(res.data.message);
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    handlePerms(row){
      this.drawerTableVisible = true
      this.perms.rid = row.id
      this.perms.name = ''
      this.perms.description = ''
      this.getPermsList()
    },
    getPermsList(){
      this.$axios.get("perms/getPermsByRid",{
        params:{
          rid:this.perms.rid,
          page:this.page,
          size:this.size
        }
      }).then(res=>{
        if(res.data.code == 200){
          this.permsList = res.data.data.data
          this.permsTotal = res.data.data.total
        }
      })
    },
    handlePermsCurrentChange(val){
      this.page = val
      this.getPermsList()
    },
    addPerms(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios.post("/perms/addPerms",this.perms).then(res=>{
            if(res.data.code == 200){
              this.$message({
                message: '添加成功',
                type: 'success'
              });
              this.getPermsList()
            }
          }) 
        } else {
          return false;
        }
      }); 
    },
    handleEditPerms(row){
      console.log(row)
      this.newPerms = {
        id:row.id,
        name:row.name,
        description:row.description
      }
      this.dialogPermsVisible = true
    },
    handleConfirmPerms(formName){
      this.$refs[formName].validate((valid) => {
        if(valid){
          this.$axios.put("/perms/editPerms",this.newPerms).then(res=>{
            if(res.data.code == 200){
              this.$message({
                message: '修改成功',
                type: 'success'
              });
              this.dialogPermsVisible = false
              this.getPermsList()
            }
          })
        } else {
          return false;
        }
      });
    },
    handleDeletePerms(row){
      this.$axios.delete('/perms/deletePerms/' + row.id).then(res=>{
        if (res.data.code == 200) {
          if (res.data.data){
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getPermsList()
          }
        } else {
          this.$message.error("删除失败");
        }
      })
    }
  }
}
</script>

<style scoped>
.box-card {
  margin-left:5vh;
  margin-right:2vh;
  margin-top: 3vh;
  height: 88vh;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>